﻿using System;
using uForum.Businesslogic;
using uForum.Configuration;
using umbraco.BusinessLogic;
using umbraco.cms.businesslogic;
using umbraco.cms.businesslogic.web;
using umbraco.DataLayer;
using umbDeleteEventArgs = umbraco.cms.businesslogic.DeleteEventArgs;

namespace uForum
{

    public class NewForumHandler : ApplicationBase
    {

        public NewForumHandler()
        {
            Document.BeforePublish += OnDocumentBeforePublish;
            Document.AfterDelete += OnDocumentAfterDelete;
        }

        static void OnDocumentAfterDelete(Document sender, umbDeleteEventArgs e)
        {
            try
            {
                if (sender.ContentType.Alias.Equals(ContentProperties.ForumDocumentTypeAlias, StringComparison.InvariantCultureIgnoreCase))
                {
                    var f = new Forum(sender.Id);
                    if (f.Exists)
                    {
                        f.Delete();
                        Log.Add(LogTypes.Notify, sender.Id, string.Format("uForum: Forum '{0}' has been deleted", f.Title));
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Add(LogTypes.Error, sender.Id, "uForum: NewForumHandler failed to delete forum. Exception details: " + ex);
            }
        }

        static void OnDocumentBeforePublish(Document sender, PublishEventArgs e)
        {
            try
            {
                if (sender.ContentType.Alias.Equals(ContentProperties.ForumDocumentTypeAlias, StringComparison.InvariantCultureIgnoreCase))
                {
                    var f = new Forum(sender.Id);
                    if (f.Exists)
                    {
                        f.Save();
                    }
                    else
                    {
                        int parentId = sender.Level == 1 ? -1 : sender.Parent.Id;
                        Forum.Create(sender.Id, parentId, sender.sortOrder);
                    }
                }
            }
            catch (SqlHelperException ex)
            {
                //Cancel the publish
                e.Cancel = true;

                //Log the error
                Log.Add(LogTypes.Error, sender.Id, "uForum: NewForumHandler failed to create/update forum. Check that the uForum tables exist in the database. Exception details: " + ex);
            }
            catch (Exception ex)
            {
                //Cancel the publish
                e.Cancel = true;

                //Log the error
                Log.Add(LogTypes.Error, sender.Id, "uForum: NewForumHandler failed to create/update forum. Exception details: " + ex);
            }
        }
    }
}
